package cn.qingfeng.a006_rpc2.client;

import cn.qingfeng.a006_rpc2.message.RpcRequestMessage;
import cn.qingfeng.a006_rpc2.protocol.MessageCodoc;
import cn.qingfeng.a006_rpc2.protocol.ProtocolFrameDecoder;
import cn.qingfeng.a006_rpc2.protocol.SequenceIdGenerator;
import cn.qingfeng.a006_rpc2.server.handler.RpcResponseMessageHandler;
import cn.qingfeng.a006_rpc2.server.service.HelloService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Proxy;

@Slf4j
public class RpcClientManager {
    public static void main(String[] args) {
        HelloService service = getProxyService(HelloService.class);
        System.out.println("打印：" + service.sayHello("张三"));
    }

    @SuppressWarnings("unchecked")
    public static <T> T getProxyService(Class<T> serviceClass) {
        ClassLoader loader = serviceClass.getClassLoader();
        Class<?>[] interfaces = new Class[]{serviceClass};
        Object result = Proxy.newProxyInstance(loader, interfaces, (proxy, method, args) -> {
            // 1. 将方法调用转换为 消息对象
            int sequenceId = SequenceIdGenerator.nextId();
            RpcRequestMessage msg = new RpcRequestMessage(
                    sequenceId,
                    serviceClass.getName(),
                    method.getName(),
                    method.getReturnType(),
                    method.getParameterTypes(),
                    args
            );

            // 2. 将消息对象发送出去
            getChannel().writeAndFlush(msg);

            // 3. 准备一个空 Promise 对象，来接收结果
            // - 因为代理和RpcResponseMessageHandler不是同一个线程，代理类要想拿到结果就得跨线程与handler通信。
            // - 指定 promise 对象异步接收结果线程，目的是将promise与这个线程绑定
            DefaultPromise<Object> promise = new DefaultPromise<>(getChannel().eventLoop());
            RpcResponseMessageHandler.PROMISE_MAP.put(sequenceId, promise);

            // 4. 阻塞，等待 promise 结果。一旦RpcResponseMessageHandler中修改了promise的值，这里就会结束阻塞。
            promise.await();
            if (promise.isSuccess()) {
                // 调用正常
                return promise.getNow();
            } else {
                throw new RuntimeException(promise.cause());
            }
        });

        return (T) result;
    }

    private static Channel channel = null;
    private static final Object LOCK = new Object();

    // 获取唯一的 channel 对象 单例模式
    public static Channel getChannel() {
        if (channel != null) {
            return channel;
        }

        synchronized (LOCK) {
            if (channel != null) {
                return channel;
            }
            initChannel();
            return channel;
        }
    }

    // 初始化 channel 方法 等于是新建一个channel来发消息
    private static void initChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new ProtocolFrameDecoder());
                        channel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        channel.pipeline().addLast(new MessageCodoc());
                        channel.pipeline().addLast(new RpcResponseMessageHandler());
                    }
                });
        try {
            channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().addListener(fature -> {
                group.shutdownGracefully();
            });
        } catch (InterruptedException e) {
            log.error("client error", e);
        }
    }
}
